const express = require('express');
const fs = require('fs');
const mime = require('mime')

const { fileDownloadPath } = require('../config/setting')

const router = express.Router()

router.get('/', (req, res) => {
    const {filename} = req.query;

    if (filename && fs.existsSync(fileDownloadPath + filename)) {
        const mimeType = mime.getType(filename);
        res.setHeader('Content-type', mimeType);

        // IE自求多福
        res.setHeader('Content-Disposition', 'attachment;filename=' + new Buffer.from(filename).toString('binary'));

        console.log('download')

        // 读取文件并返回
        const rs = fs.createReadStream(fileDownloadPath + filename);
        return rs.pipe(res)
    }

    // 文件不存在
    return res.send({
        code: 404,
        msg: 'not found ' + filename
    })
})

module.exports = router